<?php
namespace app\controllers\h5\my;

use app\award\Award;
use app\award\Up;
use app\commission\ReceivedCommission;
use app\controllers\h5\base\H5Controller;

use app\models\order\Order;
use app\models\order\Order as Model;
use app\models\order\OrderItem;
use app\models\order\OrderLogistics;
use app\models\OrderRe;
use app\models\product\Product;
use app\models\product\ProductArea;
use app\models\product\ProductAreaList;
use app\models\SetUserUp;
use app\models\system\SetExpressCompany;
use app\models\user\UserAccount;
use app\util\BirdExpress;

/**
 * my order
 *
 * Class Order
 * @package app\controllers\h5\my
 */
class OrderController extends H5Controller
{
    public function actionList()
    {
        $s = intval($this->post('status'));

        // status: h5 to model
        switch ($s) {
            case 1:
                $status = Model::$statusMapping['FINISH'];
                break;
            case 2:
                $status = Model::$statusMapping['NON_PAYMENT'];
                break;
            case 3:
                $status = Model::$statusMapping['PAID'];
                break;
            case 4:
                $status = Model::$statusMapping['WAIT_RECEIVING'];
                break;
            case 5:
                $status = Model::$statusMapping['RECEIVED'];
                break;
            case 6:
                $status = Model::$statusMapping['SERVICE'];
                break;
            case 7:
                $status = Model::$statusMapping['CANCEL'];
                break;
            default:
                $status = Model::$statusMapping['ALL'];
        }

        $page = intval($this->post('page', $this->page));
        $pageSize = intval($this->post('pageSize', $this->pageSize));

        $query = Model::find()
            ->andWhere(['user_id' => $this->user->id])
            ->andWhere(['!=', 'status', Model::$statusMapping['DELETE']]);

        if ($status > Model::$statusMapping['ALL']) {
            $query->andWhere(['status' => $status]);
        }

        $totalCount = $query->count();
        $totalPage = ceil($totalCount / $pageSize);

        $list = $query->orderBy(['id' => SORT_DESC])
            ->offset(($page - 1) * $pageSize)
            ->limit($pageSize)
            ->with([
                'item', 'item.product', 'item.product.mainImage', 'item.logistics', 'item.logistics.company',
                'address', 'address.city', 'item.active0'
            ])
            ->asArray()
            ->all();

        foreach ($list as &$item) {
            $item['address']['nickname'] = base64_decode($item['address']['nickname']);
            $activeList = [];
            foreach ($item['item'] as $v) {
                if ($v['active0']) {
                    // array_push($activeList, $v['active0']);
                    foreach ($v['active0'] as $x) {
                        array_push($activeList, $x);
                    }
                }
            }
            $item['active_list'] = $activeList;
        }

        // var_dump($list);exit;
        // var_dump($list[0]['item'][0]['active0']);exit;

        return $this->successEncode([
            $this->list => $list,
            $this->totalCount => (int)$totalCount,
            $this->totalPage => $totalPage,
            $this->currentPage => $page
        ]);
    }

    /**
     * reset pay order
     *
     * @return array|string[]|\yii\web\Response
     */
    public function actionResetPay()
    {
        $order_id = intval($this->post('order_id'));

        $order = Model::findOne(['id' => $order_id]);

        if (!$order || $order->user_id != $this->user->id || $order->status != Model::$statusMapping['NON_PAYMENT']) {
            return $this->fail('错误操作');
        }

        $order->sn = Model::generateSn();
        if ($order->save()) {
            return $this->success();
        }

        return $this->fail();
    }

    public function actionFinish()
    {
        $order_id = intval($this->post('order_id'));

        $order = Model::findOne(['id' => $order_id]);

        if (!$order || $order->user_id != $this->user->id || $order->status != Model::$statusMapping['SERVICE']) {
            return $this->fail('错误操作');
        }

        $order->status = Model::$statusMapping['FINISH'];
        if ($order->save()) {
            return $this->success();
        }

        return $this->fail();
    }

    public function actionDelete()
    {
        $order_id = intval($this->post('order_id'));

        $order = Model::findOne(['id' => $order_id]);

        if (!$order || $order->user_id != $this->user->id) {
            if ($order->status != Model::$statusMapping['CANCEL'] || $order->status != Model::$statusMapping['NON_PAYMENT']) {
                return $this->fail('错误操作');
            }
        }

        $order->status = Model::$statusMapping['DELETE'];
        if ($order->save()) {

            // 退回余额
            $account = UserAccount::findOne(['user_id' => $order->user_id]);
            if ($account) {
                if ($account->lock_balance >= $order->use_balance) {
                    $account->lock_balance -= $order->use_balance;
                    $account->balance += $order->use_balance;
                }

                if ($account->lock_score >= $order->use_score) {
                    $account->lock_score -= $order->use_score;
                    $account->score += $order->use_score;
                }

                if ($account->lock_platform_ticket >= $order->use_platform_ticket) {
                    $account->lock_platform_ticket -= $order->use_platform_ticket;
                    $account->platform_ticket += $order->use_platform_ticket;
                }

                $account->save();
            }

            return $this->success();
        }

        return $this->fail();
    }

    public function actionUrge()
    {
        $order_id = intval($this->post('order_id'));

        $order = Model::findOne(['id' => $order_id]);

        if (!$order || $order->user_id != $this->user->id || $order->status != Model::$statusMapping['PAID']) {
            return $this->fail('错误操作');
        }

        return $this->success();
    }

    public function actionConfirmReceived()
    {
        $order_id = intval($this->post('order_id'));

        $order = Model::findOne(['id' => $order_id]);

        if (!$order || $order->user_id != $this->user->id || $order->status != Model::$statusMapping['WAIT_RECEIVING']) {
            return $this->fail('错误操作');
        }

        $order->status = Model::$statusMapping['RECEIVED'];
        if ($order->save()) {

            // commission
            ReceivedCommission::done($order->id);

            return $this->success();
        }

        return $this->fail();
    }

    public function actionExpress()
    {
        $logistics_id = $this->post('logistics_id');

        $model = OrderLogistics::findOne(['id' => $logistics_id]);

        if ($model) {
            $code = SetExpressCompany::find()
                ->where(['id' => $model->express_company_id])
                ->select(['code'])
                ->scalar();

            // var_dump($code, $model->express_sn);exit;

            // 写屎
            $code = 'JD';

            $express = BirdExpress::getOrderTracesByJson($code, $model->express_sn);

            // var_dump($express);exit;

            if ($express) {
                return $this->successEncode([
                    'express' => $express
                ]);
            }
        }

        return $this->fail();

    }

    // 激活订单
    public function actionActive()
    {
        $id = $this->post('id');
        $code = $this->post('code');

        $order = Order::findOne(['id' => $id]);

        if ($order) {
            if ($order->active_ok == 1) {
                return $this->fail('重复操作');
            }

            if (strtolower($code) != strtolower($order->active)) {
                return $this->fail('激活码错误');
            }

            $order->active_ok = 1;
            $order->save();

            new Award($order);
            new Up($order);

            return $this->success();
        }
    }

    // 回寄信息显示
    public function actionRe()
    {
        $product_id = $this->post('product_id');
        $sn = $this->post('sn');

        $show = ProductArea::checkMaterial($product_id);
        $set = SetUserUp::getLastOne();

        $model = OrderRe::findOne(['sn' => $sn]);
        if ($model) {
            $logistics = $model->logistics;
            $status = $model->status;
            $real_amount = $model->real_amount;
        } else {
            $logistics = '';
            $status = 0;
            $real_amount = 0;
        }

        return $this->successEncode([
            'show' => $show,
            'address' => $set->re_address,
            'name' => $set->re_name,
            'mobile' => $set->re_mobile,
            'logistics' => $logistics,
            'status' => $status,
            'real_amount' => $real_amount,
        ]);
    }

    // 保存回寄
    public function actionReSave()
    {
        $sn = $this->post('sn');
        $logistics = $this->post('logistics');

        $order = Order::findOne(['sn' => $sn]);
        if (!$order) {
            return $this->fail();
        }

        if ($order->status == Order::$statusMapping['CANCEL']
        || $order->status == Order::$statusMapping['DELETE']
        || $order->status == Order::$statusMapping['NON_PAYMENT']
        || $order->status == Order::$statusMapping['REFUND']) {
            return $this->fail('订单状态错误');
        }

        $model = OrderRe::findOne(['sn' => $sn]);

        if ($model) {
            if ($model->status >= 1) {
                return $this->fail('订单已经完成');
            } else {
                $model->logistics = $logistics;
                $model->save();

                $order->status = Order::$statusMapping['RE'];
                $order->save();

                return $this->success();
            }
        }

        $model = new OrderRe();
        $model->sn = $sn;
        $model->user_id = $this->user->id;
        $model->status = 0;
        $model->amount = $this->getReAmount($order);
        $model->logistics = $logistics;
        $model->save();

        if ($model->save()) {

            $order->status = Order::$statusMapping['RE'];
            $order->save();

            return $this->success();
        }
    }

    // 计算金额
    private function getReAmount(Order $order)
    {
        $items = OrderItem::find()
            ->where(['order_id' => $order->id])
            ->all();

        $sum = 0;
        foreach ($items as $item) {
            $product = Product::find()
                ->where(['id' => $item['product_id']])
                ->with(['commissionDiff'])
                ->asArray()
                ->one();

            // var_dump($item['quantity'], $product['price'], $product['commissionDiff']['material']);
            // exit;

            $sum += ($product['price'] + $product['commissionDiff']['material']) * $item['quantity'];
        }

        return $sum;
    }
}